package com.realbrand.net.realbrandpay.ui.activity.mall;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.adapter.MallCarAdapter;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.base.FirstActivity;
import com.realbrand.net.realbrandpay.bean.AllMallCarBean;
import com.realbrand.net.realbrandpay.bean.BrandBean;
import com.realbrand.net.realbrandpay.bean.CommodityBean;
import com.realbrand.net.realbrandpay.bean.ConfirmOrderBean;
import com.realbrand.net.realbrandpay.bean.MollCarBean;
import com.realbrand.net.realbrandpay.ui.activity.ADSActivity;
import com.realbrand.net.realbrandpay.ui.activity.gradevin.GradevinActivity;
import com.realbrand.net.realbrandpay.ui.activity.login.LoginActivity;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.ShopCarActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.WalletActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.set.WalletLogoutActivity;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.weight.SmoothCheckBox;
import com.realbrand.net.realbrandpay.zxing.app.CaptureActivity;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/4/23.
 */

public class MallCarActivity extends FirstActivity implements IViewMallCar, IViewUpdata, IViewUpdataDeailResult {
    @BindView(R.id.shopcar_toolBar_tv_clean)
    TextView shopcarToolBarTvClean;
    @BindView(R.id.shopcar_roolBar)
    Toolbar shopcarRoolBar;
    @BindView(R.id.mallCar_tv_shopCar)
    TextView mallCarTvShopCar;
    @BindView(R.id.mallCar_elv)
    ExpandableListView mallCareElv;
    @BindView(R.id.mallCar_cb_all)
    SmoothCheckBox mallCarBtAll;
    @BindView(R.id.mallCar_tv_sumMoney)
    TextView mallCarTvSumMoney;
    @BindView(R.id.mallCar_bt_checked)
    Button mallCarBtChecked;
    @BindView(R.id.shopcar_tv_scan)
    TextView shopcarTvScan;
    @BindView(R.id.shopcar_tv_mall)
    TextView shopcarTvMall;
    @BindView(R.id.shopcar_tv_my)
    TextView shopcarTvMy;
    SharedPreferences sharedPreferences;
    String UserName;

    PersenterUpdataDeailResult persenterUpdataDeailResult;
    PersenterMollCarGetData persenterMollCarGetData;
    MallCarAdapter mallCarAdapter;
    AllMallCarBean allMallCarBean;
//    @BindView(R.id.mallCar_tv_gradevin)
//    TextView mallCarTvGradevin;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        shopcarRoolBar.setTitle("");
        shopcarToolBarTvClean.setText("删除");
        setSupportActionBar(shopcarRoolBar);
        //获取用户名
        sharedPreferences = getSharedPreferences("userMassage", MODE_PRIVATE);
        UserName = sharedPreferences.getString("account", "");
        //初始化Persenter
        initData();
        //进行网络请求获取数据
        getMallCarData();
        setOnClick();
    }

    private void getMallCarData() {
        JSONObject object = new JSONObject();
        try {
            object.put("METHOD", "SelectCommodityInfo");
            object.put("SOURCE", "MallCarActivity");
            object.put("CREDENTIALS", "0");
            object.put("TERMINAL", "0");
            object.put("INDEX", Static.getDay());
            object.put("UserAccount", UserName);
            persenterMollCarGetData.getData(object.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void initData() {
        persenterMollCarGetData = new PersenterMollCarGetData();
        persenterMollCarGetData.attachView(this);
        persenterUpdataDeailResult = new PersenterUpdataDeailResult();
        persenterUpdataDeailResult.attachView(this);
        //去掉ExpandableListView默认的箭头
        mallCareElv.setGroupIndicator(null);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.mallcar_layout;
    }

    @Override
    protected void setOnClick() {
        shopcarTvMall.setOnClickListener(this);
        shopcarTvMy.setOnClickListener(this);
        shopcarTvScan.setOnClickListener(this);
        mallCarTvShopCar.setOnClickListener(this);
        mallCarBtAll.setOnClickListener(this);
        mallCarBtChecked.setOnClickListener(this);
        shopcarToolBarTvClean.setOnClickListener(this);
//        mallCarTvGradevin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Object vTag = v.getTag();
        switch (v.getId()) {
            //钱包
            case R.id.shopcar_tv_my:
                if (LoginActivity.isLogin) {
                    startActivity(new Intent(this, WalletActivity.class));
                } else {
                    startActivity(new Intent(this, WalletLogoutActivity.class));
                }
                finish();
                break;
            //扫码
            case R.id.shopcar_tv_scan:
                Intent intent = new Intent(this, CaptureActivity.class);
                Bundle bundle_scan = new Bundle();
                bundle_scan.putString(Static.BundleKey, ADSActivity.VALUE_ADS);
                intent.putExtras(bundle_scan);
                startActivity(intent);
                break;
            //h5商城
            case R.id.shopcar_tv_mall:
                startActivity(new Intent(this, MallActivity.class));
                finish();
                break;
            //线下购物车
            case R.id.mallCar_tv_shopCar:
                startActivity(new Intent(this, ShopCarActivity.class));
                finish();
                break;
            //智能酒柜
//            case R.id.mallCar_tv_gradevin:
//                startActivity(new Intent(this, GradevinActivity.class));
//                finish();
//                break;
            //全选
            case R.id.mallCar_cb_all:
                selectAll();
                break;
            //结算
            case R.id.mallCar_bt_checked:
                if (allMallCarBean != null) {
                    checkOrder();
                } else {
                    Static.toast(this, "请添加商品进行结算");
                }
                break;
            //删除
            case R.id.shopcar_toolBar_tv_clean:
                clear();
                break;
            //加
            case R.id.mallCar_lv_itemTwo_ib_add:
                String tag = vTag.toString();
                String[] split;
                int groupId = 0;
                int childId = 0;
                int allCount = allMallCarBean.getAllCount();
                double allMoney = allMallCarBean.getAllMoney();
                if (tag.contains(",") && tag != null) {
                    split = tag.split(",");
                    groupId = Integer.parseInt(split[0]);
                    childId = Integer.parseInt(split[1]);
                }
                String goodCount = allMallCarBean.getContent().get(groupId).getList().get(childId).getCommoditySum();
                allMallCarBean.getContent().get(groupId).getList().get(childId).setCommoditySum(addCount(goodCount));
                if (allMallCarBean.getContent().get(groupId).getList().get(childId).isCommoditySelect()) {
                    allMoney += Double.parseDouble(allMallCarBean.getContent().get(groupId).getList().get(childId).getCommodityPrice());
                    update(allMallCarBean.isAllSelect(), allCount, allMoney);
                }
                allMallCarBean.setAllMoney(allMoney);
                mallCarAdapter.notifyDataSetChanged();
                //获取是否更新数据成功
                isUpdataSuccess(allMallCarBean.getContent().get(groupId).getList().get(childId).getCommoditySum(), allMallCarBean.getContent().get(groupId).getList().get(childId).getCommodityName(),
                        allMallCarBean.getContent().get(groupId).getList().get(childId).getCommodityPrice());
                break;
            //减
            case R.id.mallCar_lv_itemTwo_ib_delete:
                String tag1 = vTag.toString();
                String[] split1;
                int groupId1 = 0;
                int childId1 = 0;
                int allCount1 = allMallCarBean.getAllCount();
                double allMoney1 = allMallCarBean.getAllMoney();
                if (tag1.contains(",") && tag1 != null) {
                    split = tag1.split(",");
                    groupId1 = Integer.parseInt(split[0]);
                    childId1 = Integer.parseInt(split[1]);
                }
                String goodCount1 = allMallCarBean.getContent().get(groupId1).getList().get(childId1).getCommoditySum();
                if (Integer.valueOf(goodCount1) > 1) {
                    allMallCarBean.getContent().get(groupId1).getList().get(childId1).setCommoditySum(reduceCount(goodCount1));
                    if (allMallCarBean.getContent().get(groupId1).getList().get(childId1).isCommoditySelect()) {
                        allMoney1 -= Double.parseDouble(allMallCarBean.getContent().get(childId1).getList().get(childId1).getCommodityPrice());
                        update(allMallCarBean.isAllSelect(), allCount1, allMoney1);
                    }
                    allMallCarBean.setAllMoney(allMoney1);
                    mallCarAdapter.notifyDataSetChanged();
                    isUpdataSuccess(allMallCarBean.getContent().get(groupId1).getList().get(childId1).getCommoditySum(), allMallCarBean.getContent().get(groupId1).getList().get(childId1).getCommodityName(),
                            allMallCarBean.getContent().get(groupId1).getList().get(childId1).getCommodityPrice());
                }
                break;
        }
    }

    /**
     * 查询更新商品数量是否是否成功
     *
     * @param goodCount
     * @param commodityName
     * @param commodityPrice
     */
    private void isUpdataSuccess(String goodCount, String commodityName, String commodityPrice) {
        JSONObject upDataDealJson = new JSONObject();
        try {
            upDataDealJson.put("METHOD", "UpdateDealSum");
            upDataDealJson.put("SOURCE", "MallCarActivity");
            upDataDealJson.put("CREDENTIALS", "0");
            upDataDealJson.put("TERMINAL", "0");
            upDataDealJson.put("INDEX", Static.getDay());
            upDataDealJson.put("CommodityName", commodityName);
            upDataDealJson.put("DealSum", goodCount);
            upDataDealJson.put("DealMoney", commodityPrice);
            upDataDealJson.put("UserAccount", UserName);
            L.d(L.TAG, "更新商品传过去的数据" + "数量" + goodCount);
            persenterUpdataDeailResult.getUpdataDeailResult(upDataDealJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
            L.d(L.TAG, "更新商品数量的结果异常" + e.toString());
        }
    }

    /**
     * 删除
     */
    private void clear() {
        List<String> commodityNumberList = new ArrayList<>();
        if (allMallCarBean.isAllSelect()) {

            for (int i = 0; i < allMallCarBean.getContent().size(); i++) {
                for (int n = 0; n < allMallCarBean.getContent().get(i).getList().size(); n++) {
                    commodityNumberList.add(allMallCarBean.getContent().get(i).getList().get(n).getCommodityNumber());
                }
            }
            allMallCarBean.getContent().clear();
            mallCarAdapter.notifyDataSetChanged();
        } else {
            for (int i = 0; i < allMallCarBean.getContent().size(); i++) {
                for (int n = 0; n < allMallCarBean.getContent().get(i).getList().size(); n++) {
                    if (allMallCarBean.getContent().get(i).getList().get(n).isCommoditySelect()) {
                        commodityNumberList.add(allMallCarBean.getContent().get(i).getList().get(n).getCommodityNumber());
                        allMallCarBean.getContent().get(i).getList().remove(allMallCarBean.getContent().get(i).getList().get(n));
                        mallCarAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
        String stringCommodityNameList = Static.stringScan(commodityNumberList);
        L.d(L.TAG, "数组" + stringCommodityNameList);
        try {
            String encode = URLEncoder.encode(stringCommodityNameList, "utf-8");
            String s = "\"CommodityNumber\":" + encode;
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("METHOD", "DelCommodityInfo");
            jsonObject1.put("SOURCE", "MallCarActivity");
            jsonObject1.put("CREDENTIALS", "0");
            jsonObject1.put("TERMINAL", "0");
            jsonObject1.put("INDEX", Static.getDay());
            jsonObject1.put("CommodityNumber", s);
            jsonObject1.put("UserAccount", UserName);
            L.d(L.TAG, "删除参数" + jsonObject1.toString());
            persenterUpdataDeailResult.deleteResult(jsonObject1.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void checkOrder() {
        List<ConfirmOrderBean> orderList = new ArrayList<>();
        //1、判断购物车里的所有数据是否全都被选中
        //2、在没有全被选中的情况下，循环购物车内的所有品牌
        //3、判断循环到的品牌内的所以商品是否被选中
        //4、循环到的品牌内如果不是全都被选中的话，那就循环该品牌内的所以商品
        //5、判断该品牌内的哪个商品被选中
        if (allMallCarBean.isAllSelect()) {
            for (BrandBean brandBean : allMallCarBean.getContent()) {
                for (CommodityBean commodityBean : brandBean.getList()) {
                    ConfirmOrderBean confirmOrderBean = new ConfirmOrderBean();
                    confirmOrderBean.setBrandLog(brandBean.getBrandLog());
                    confirmOrderBean.setBrandName(brandBean.getBrandName());
                    confirmOrderBean.setCommodityLog(commodityBean.getCommodityLog());
                    confirmOrderBean.setCommodityName(commodityBean.getCommodityName());
                    confirmOrderBean.setCommodityPricel(commodityBean.getCommodityPrice());
                    confirmOrderBean.setCommoditySum(commodityBean.getCommoditySum());
                    confirmOrderBean.setCommodityNumber(commodityBean.getCommodityNumber());
                    orderList.add(confirmOrderBean);
                }
            }
        } else {

            for (BrandBean brandBean : allMallCarBean.getContent()) {
                if (brandBean.isSelect()) {
                    for (CommodityBean commodityBean : brandBean.getList()) {
                        ConfirmOrderBean confirmOrderBean = new ConfirmOrderBean();
                        confirmOrderBean.setBrandLog(commodityBean.getBrandLog());
                        confirmOrderBean.setBrandName(commodityBean.getBrandName());
                        confirmOrderBean.setCommoditySum(commodityBean.getCommoditySum());
                        confirmOrderBean.setCommodityPricel(commodityBean.getCommodityPrice());
                        confirmOrderBean.setCommodityName(commodityBean.getCommodityName());
                        confirmOrderBean.setCommodityLog(commodityBean.getCommodityLog());
                        confirmOrderBean.setCommodityNumber(commodityBean.getCommodityNumber());
                        orderList.add(confirmOrderBean);
                    }
                } else {
                    for (CommodityBean commodityBean : brandBean.getList()) {
                        if (commodityBean.isCommoditySelect()) {
                            ConfirmOrderBean confirmOrderBean = new ConfirmOrderBean();
                            confirmOrderBean.setBrandLog(commodityBean.getBrandLog());
                            confirmOrderBean.setBrandName(commodityBean.getBrandName());
                            confirmOrderBean.setCommoditySum(commodityBean.getCommoditySum());
                            confirmOrderBean.setCommodityPricel(commodityBean.getCommodityPrice());
                            confirmOrderBean.setCommodityName(commodityBean.getCommodityName());
                            confirmOrderBean.setCommodityLog(commodityBean.getCommodityLog());
                            confirmOrderBean.setCommodityNumber(commodityBean.getCommodityNumber());
                            orderList.add(confirmOrderBean);
                        }
                    }
                }
            }

        }
        L.d(L.TAG, "商品详情" + orderList.toString());
        if (orderList.size() == 0) {
            mallCarBtChecked.setEnabled(false);
        } else {
            mallCarBtChecked.setEnabled(true);
            Intent intent = new Intent(MallCarActivity.this, ConfirmOrderActivtiy.class);
            intent.putExtra("orderList", (Serializable) orderList);
            startActivity(intent);
        }

    }

    /**
     * 全选
     */
    private void selectAll() {
        int allCount = allMallCarBean.getAllCount();
        double allMoney = allMallCarBean.getAllMoney();
        if (!mallCarBtAll.isChecked()) {
            allMallCarBean.setAllSelect(true);
            for (int i = 0; i < allMallCarBean.getContent().size(); i++) {
                allMallCarBean.getContent().get(i).setSelect(true);
                for (int n = 0; n < allMallCarBean.getContent().get(i).getList().size(); n++) {
                    if (!allMallCarBean.getContent().get(i).getList().get(n).isCommoditySelect()) {
                        allCount++;
                        allMoney += Double.parseDouble(allMallCarBean.getContent().get(i).getList().get(n).getCommoditySum())
                                * Double.parseDouble(allMallCarBean.getContent().get(i).getList().get(n).getCommodityPrice());
                        allMallCarBean.getContent().get(i).getList().get(n).setCommoditySelect(true);
                    }
                }
            }
        } else {
            allMallCarBean.setAllSelect(false);
            for (int i = 0; i < allMallCarBean.getContent().size(); i++) {
                allMallCarBean.getContent().get(i).setSelect(false);
                for (int n = 0; n < allMallCarBean.getContent().get(i).getList().size(); n++) {
                    allMallCarBean.getContent().get(i).getList().get(n).setCommoditySelect(false);
                }
                allCount = 0;
                allMoney = 0;
            }
        }
        allMallCarBean.setAllMoney(allMoney);
        allMallCarBean.setAllCount(allCount);
        update(allMallCarBean.isAllSelect(), allCount, allMoney);
        mallCarAdapter.notifyDataSetChanged();
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showFailMsg(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public Context getContext() {
        return MallCarActivity.this;
    }

    StringBuffer stringBuffer;

    /**
     * 获取所有数据填充到listview
     *
     * @param data
     */
    @Override
    public void showData(List<MollCarBean> data) {
        List<BrandBean> allList = init(data);
        allMallCarBean = new AllMallCarBean();
        allMallCarBean.setContent(allList);
        L.d(L.TAG, "商品所以数据" + allList.toString());
        mallCarAdapter = new MallCarAdapter(MallCarActivity.this, allMallCarBean);
        mallCarAdapter.setChangedListener(this);
        mallCarAdapter.setOnAddNum(this);
        mallCarAdapter.setOnRemove(this);
        mallCareElv.setAdapter(mallCarAdapter);
        //展开所有分组
        for (int i = 0; i < allMallCarBean.getContent().size(); i++) {
            mallCareElv.expandGroup(i);
        }
    }

    private List<BrandBean> init(List<MollCarBean> data) {
        List<BrandBean> brandBeenList = new ArrayList<BrandBean>();
        brandBeenList.clear();
        for (int i = 0; i < data.get(0).getBrandName().size(); i++) {
            CommodityBean commodityBean = new CommodityBean();
            commodityBean.setCommodityLog(data.get(0).getFilePath().get(i));
            commodityBean.setCommodityName(data.get(0).getCommodityName().get(i));
            commodityBean.setCommodityPrice(data.get(0).getSupplyMoney().get(i));
            commodityBean.setCommoditySum(data.get(0).getDealSum().get(i));
            commodityBean.setBrandName(data.get(0).getBrandName().get(i));
            commodityBean.setBrandLog(data.get(0).getBrandLogo().get(i));
            commodityBean.setCommodityNumber(data.get(0).getCommodityNumber().get(i));
            commodityBean.setCommoditySelect(false);
            if (brandBeenList.size() == 0) {
                List<CommodityBean> commodityBeanList = new ArrayList<CommodityBean>();
                commodityBeanList.add(commodityBean);
                BrandBean brandBean = new BrandBean();
                brandBean.setBrandLog(data.get(0).getBrandLogo().get(i));
                brandBean.setBrandName(data.get(0).getBrandName().get(i));
                brandBean.setSelect(false);
                brandBean.setList(commodityBeanList);
                brandBeenList.add(brandBean);
            } else {
                int j = -1;

                for (int a = 0; a < brandBeenList.size(); a++) {
                    BrandBean brandBean2 = brandBeenList.get(a);
                    if (brandBean2.getBrandName().equals(commodityBean.getBrandName())) {
                        brandBean2.getList().add(commodityBean);
                        j = a;
                    }
                }
                if (j < 0) {
                    List<CommodityBean> commodityBeanList1 = new ArrayList<CommodityBean>();
                    commodityBeanList1.add(commodityBean);
                    BrandBean brandBea1 = new BrandBean();
                    brandBea1.setBrandLog(data.get(0).getBrandLogo().get(i));
                    brandBea1.setBrandName(data.get(0).getBrandName().get(i));
                    brandBea1.setSelect(false);
                    brandBea1.setList(commodityBeanList1);
                    brandBeenList.add(brandBea1);
                }
            }
        }
        return brandBeenList;
    }


    @Override
    public void update(boolean isAllSelected, int count, double price) {
        L.d(L.TAG, "总价格" + price);

        mallCarTvSumMoney.setText(new DecimalFormat("0.00").format(price));
        mallCarBtAll.setChecked(isAllSelected);
    }

    private String reduceCount(String var) {
        Integer integer = Integer.valueOf(var);
        if (integer > 1) {
            integer--;
        }
        return integer + "";
    }

    private String addCount(String var) {
        Integer integer = Integer.valueOf(var);
        integer++;
        return integer + "";
    }


    /**
     * 获取更新商品数量的结果
     *
     * @param data
     */
    @Override
    public void showResult(String data) {
        if ("200".equals(data)) {
        } else {
            getMallCarData();
            mallCarAdapter.notifyDataSetChanged();
            Static.toast(MallCarActivity.this, "库存不足");
        }

    }

    //删除是否成功
    @Override
    public void showDeleteResult(String data) {
        if ("200".equals(data)) {
            getMallCarData();
            mallCarAdapter.notifyDataSetChanged();
            mallCarTvSumMoney.setText("0.00");
            mallCarBtAll.setChecked(false);
        } else {
            Static.toast(MallCarActivity.this, "删除失败");
        }
    }
}
